package com.example.demo.order.service.impl;

import com.example.demo.order.dto.request.PaymentRequest;
import com.example.demo.order.dto.response.PaymentResponse;
import com.example.demo.order.entity.Order;
import com.example.demo.order.enums.OrderStatusEnum;
import com.example.demo.order.exception.BusinessException;
import com.example.demo.order.service.OrderService;
import com.example.demo.order.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.math.BigDecimal;
import java.util.UUID;

/**
 * @ClassName PaymentServiceImpl
 * @Description 支付服务实现类（简化版）
 * @Author MingChang.Wei
 * @Date 2025/9/26
 **/
@Slf4j
@Service
public class PaymentServiceImpl implements PaymentService {

    @Resource
    private OrderService orderService;

    @Override
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.SERIALIZABLE, timeout = 60)
    public PaymentResponse initiatePayment(PaymentRequest request) {
        log.info("发起支付请求: orderNo={}, username={}, amount={}", 
                request.getOrderNo(), request.getUsername(), request.getAmount());
        
        try {
            // 1. 参数验证
            validatePaymentRequest(request);
            
            // 2. 查询订单验证
            Order order = orderService.getOrderByOrderNo(request.getOrderNo());
            validateOrderForPayment(order, request);
            
            // 3. 生成支付响应
            String paymentId = "PAY_" + UUID.randomUUID().toString().replace("-", "");
            String qrCodeUrl = "https://qr.example.com/pay/" + paymentId;
            
            return PaymentResponse.pending(paymentId, request.getOrderNo(), request.getAmount(), qrCodeUrl);
            
        } catch (Exception e) {
            log.error("支付失败: orderNo={}, username={}", 
                    request.getOrderNo(), request.getUsername(), e);
            return PaymentResponse.failed(request.getOrderNo(), "PAYMENT_ERROR", "支付失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean handlePaymentCallback(String orderNo, String paymentResult) {
        log.info("处理支付回调: orderNo={}, paymentResult={}", orderNo, paymentResult);
        
        try {
            Order order = orderService.getOrderByOrderNo(orderNo);
            if (order == null) {
                log.error("支付回调订单不存在, orderNo={}", orderNo);
                return false;
            }
            
            if ("SUCCESS".equals(paymentResult)) {
                // 支付成功，更新订单状态
                boolean payResult = orderService.payOrder(orderNo);
                if (payResult) {
                    log.info("支付回调处理成功: orderNo={}", orderNo);
                    return true;
                } else {
                    log.error("支付回调订单状态更新失败, orderNo={}", orderNo);
                    return false;
                }
            } else {
                log.warn("支付回调失败: orderNo={}, result={}", orderNo, paymentResult);
                return false;
            }
            
        } catch (Exception e) {
            log.error("支付回调处理异常: orderNo={}", orderNo, e);
            return false;
        }
    }

    @Override
    public String getPaymentStatus(String orderNo) {
        log.info("查询支付状态, orderNo={}", orderNo);
        
        try {
            Order order = orderService.getOrderByOrderNo(orderNo);
            if (order == null) {
                return "ORDER_NOT_FOUND";
            }
            
            // 根据订单状态返回支付状态
            switch (order.getStatus()) {
                case 1: // 已创建
                    return "PENDING";
                case 2: // 已支付
                    return "SUCCESS";
                case 3: // 已取消
                    return "CANCELLED";
                case 4: // 已退款
                    return "REFUNDED";
                default:
                    return "UNKNOWN";
            }
            
        } catch (Exception e) {
            log.error("查询支付状态失败, orderNo={}", orderNo, e);
            return "ERROR";
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean requestRefund(String orderNo, String refundAmount, String reason) {
        log.info("申请退款, orderNo={}, refundAmount={}, reason={}", orderNo, refundAmount, reason);
        
        try {
            Order order = orderService.getOrderByOrderNo(orderNo);
            if (order == null) {
                log.error("退款订单不存在: orderNo={}", orderNo);
                return false;
            }
            
            if (!order.getStatus().equals(OrderStatusEnum.PAID.getCode())) {
                log.error("订单状态不允许退款, orderNo={}, status={}", orderNo, order.getStatus());
                return false;
            }
            
            // 验证退款金额
            BigDecimal refundAmountDecimal = new BigDecimal(refundAmount);
            if (refundAmountDecimal.compareTo(order.getTotalAmount()) > 0) {
                log.error("退款金额超过订单金额, orderNo={}, refundAmount={}, orderAmount={}", 
                        orderNo, refundAmount, order.getTotalAmount());
                return false;
            }
            
            // 调用退款
            boolean refundResult = orderService.refundOrder(orderNo);
            if (refundResult) {
                log.info("退款处理成功, orderNo={}, refundAmount={}", orderNo, refundAmount);
                return true;
            } else {
                log.error("退款处理失败, orderNo={}", orderNo);
                return false;
            }
            
        } catch (Exception e) {
            log.error("退款处理异常, orderNo={}", orderNo, e);
            return false;
        }
    }

    /**
     * 验证支付请求参数
     */
    private void validatePaymentRequest(PaymentRequest request) {
        if (request.getAmount() == null || request.getAmount().compareTo(BigDecimal.ZERO) <= 0) {
            throw new BusinessException("支付金额必须大于0");
        }
        
        if (request.getAmount().compareTo(new BigDecimal("999999.99")) > 0) {
            throw new BusinessException("支付金额过大");
        }
    }

    /**
     * 验证订单支付条件
     */
    private void validateOrderForPayment(Order order, PaymentRequest request) {
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 验证订单所属用户
        if (!order.getUsername().equals(request.getUsername())) {
            log.warn("支付用户与订单用户不匹配: orderUser={}, payUser={}", 
                    order.getUsername(), request.getUsername());
            throw new BusinessException("订单用户验证失败");
        }
        
        // 验证订单状态
        if (!order.getStatus().equals(OrderStatusEnum.CREATED.getCode())) {
            throw new BusinessException("订单状态不允许支付");
        }
        
        // 验证支付金额
        if (order.getTotalAmount().compareTo(request.getAmount()) != 0) {
            log.warn("支付金额不匹配, orderAmount={}, payAmount={}", 
                    order.getTotalAmount(), request.getAmount());
            throw new BusinessException("支付金额不匹配");
        }
    }
}